package forum.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import forum.dao.KeyDao;
import forum.model.Keyword;
import forum.model.SectionListResult;
import forum.model.User;
import forum.service.SectionService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author haomin
 * @date 2022/06/30 11:21
 **/

@WebServlet("/section-list.json")
public class SectionListJsonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User currentUser = null;
        Keyword key = null;
        System.out.println("开始");

        HttpSession session = req.getSession(false);
        if(session != null){
            currentUser = (User) session.getAttribute("currentUser");
        }
        String keyword = new KeyDao().selectKey();

        SectionService sectionService = new SectionService();
        SectionListResult result = null;
        if(keyword == null) {
            result = sectionService.sectionListResult(currentUser);
            System.out.println("执行第一个");
        }else {
            System.out.println(keyword);
            result = sectionService.sectionListResult(currentUser,keyword);
            System.out.println("执行第二个");

        }

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().printf(jsonString);
    }
}